package eatwatch;

import java.util.*;
import javax.microedition.rms.*;

public class FieldComparator implements RecordComparator
{
	private DataDefinition  mDataDefinition = null;
	private String 			mField = null;
	private boolean			mDescending = false;

	FieldComparator (DataDefinition dataDefinition, String field)
	{
		mDataDefinition = dataDefinition;
		int spacePos = 0;
		if ((spacePos = field.indexOf (' ')) != -1) {
			mField = field.substring (0, spacePos);
			if (field.length () > spacePos)
				mDescending = field.substring (spacePos + 1).toLowerCase ().equals ("desc");
		}
		else
			mField = field;
	}

	public int compare(byte[] rec1, byte[] rec2)
	{
		Record record1 = mDataDefinition.Read (rec1);
		Record record2 = mDataDefinition.Read (rec2);

		Object value1 = record1.GetField (mField);
		Object value2 = record2.GetField (mField);

		return mDescending ? compare (value2, value1) : compare (value1, value2);
	}

	static public int compare (Object value1, Object value2)
	{
		String type = value1.getClass ().getName ();

		if (type.equals("java.lang.String"))
			return compare ((String) value1, (String) value2);
		else if (type.equals("java.lang.Float"))
			return compare ((Float) value1, (Float) value2);
		else if (type.equals("java.util.Date"))
			return compare ((Date) value1, (Date) value2);
		else if (type.equals("java.lang.Integer"))
			return compare ((Integer) value1, (Integer) value2);
		else
			throw new RuntimeException ("type not handled: " + type);
	}

	static private int compare (String value1, String value2)
	{
		int compResult = value1.compareTo (value2);
		if (compResult == 0)
			return EQUIVALENT;
		else return compResult < 0 ? PRECEDES : FOLLOWS;
	}

	static private int compare (Float value1, Float value2)
	{
		float compResult = value1.floatValue () - value2.floatValue ();
		if (compResult == 0.0f)
			return EQUIVALENT;
		else return compResult < 0 ? PRECEDES : FOLLOWS;
	}

	static private int compare (Date value1, Date value2)
	{
		long compResult = value1.getTime () - value2.getTime ();
		if (compResult == 0)
			return EQUIVALENT;
		else return compResult < 0 ? PRECEDES : FOLLOWS;
	}

	static private int compare (Integer value1, Integer value2)
	{
		int compResult = value1.intValue () - value2.intValue ();
		if (compResult == 0)
			return EQUIVALENT;
		else return compResult < 0 ? PRECEDES : FOLLOWS;
	}
}